package com.kvest.ula.network;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.kvest.ula.core.RuntimeData;
import com.kvest.ula.network.base.HTTPRequestResult;
import com.kvest.ula.network.Urls;
import com.kvest.ula.network.base.HTTPGetRequest;

import android.util.Pair;

public class GetCitiesListRequest 
{
	private HTTPGetRequest request; 
	private GetCitiesListResult resultListener;
	
	public GetCitiesListRequest(GetCitiesListResult resultListener)
    {
        this.resultListener = resultListener;
    }
	
	public void sendRequest()
    {
		request = new HTTPGetRequest(Urls.GET_CITIES_LIST);
		
		request.setResultListener(new HTTPRequestResult() 
		{	
			@Override
			public void httResponce(int code, String result) 
			{
				List<Pair<Integer, String> > resultList = new ArrayList<Pair<Integer, String> >();
				if (code == HTTPRequestResult.RESULT_OK)
                {
					boolean parsed = parseCities(result, resultList);
					resultListener.citiesListResult(parsed ? GetCitiesListResult.OK_RESULT : GetCitiesListResult.ERROR_RESULT, resultList);
                }
				else if (code == HTTPRequestResult.RESULT_ERROR)
                {
                    resultListener.citiesListResult(GetCitiesListResult.ERROR_RESULT, resultList);
                }
			}
		});
		
		request.start();
    }
	
	private boolean parseCities(String jsonStr, List<Pair<Integer, String> > cities)
	{
		JSONArray citiesArray;
        try
        {
        	citiesArray = new JSONArray(jsonStr);
        }
        catch (JSONException jex)
        {
            return false;
        }
        
        JSONObject city;
        RuntimeData rd = RuntimeData.getInstance();
        for (int i = 0; i < citiesArray.length(); ++i)
        {
            try
            {
                city = citiesArray.getJSONObject(i);
                cities.add(new Pair<Integer, String>(city.getInt("id"), city.getString("name")));

                rd.setUpdateTime(Integer.valueOf(city.getInt("id")), Long.valueOf(city.getLong("update_time")));
            }
            catch (JSONException jex)
            {
            }
        }
        
        return true;
	}
	
	public void interrupt()
    {
    	if (request != null)
    	{
    		request.interrupt();
    	}
    }
	
	public interface GetCitiesListResult
    {
        public static final int OK_RESULT = 0;
        public static final int ERROR_RESULT = 1;

        public abstract void citiesListResult(int resultType, List<Pair<Integer, String> > cities);
    }
}
